<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="隐患序号" prop="hazardId">
                <el-input v-model="queryParams.hazardId" placeholder="请输入隐患序号" clearable
                          style="width: 130px" @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="通知状态" prop="handled">
                <el-select v-model="queryParams.handled" placeholder="请选择通知状态" filterable clearable
                           style="width: 130px">
                    <el-option v-for="dict in handleOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="通知类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择通知类型" clearable style="width: 130px">
                    <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="通知时间" style="width: 274px">
                <el-date-picker v-model="dateRangeReceive" value-format="YYYY-MM-DD" type="daterange"
                                range-separator="-" start-placeholder="开始日期"
                                end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="已读时间" style="width: 274px">
                <el-date-picker v-model="dateRangeHandle" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                           v-hasPermi="['hazard:alarm:record:export']">
                    导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="list">
            <el-table-column v-for="col in columns.filter(c=>c.visible)" v-bind="col">
                <template v-if="col.slotName=='handle'" #default="{row}">
                    <el-tag :type="row.handled?'success':'danger'">{{ row.handled ? '已读' : '未读' }}</el-tag>
                </template>
                <template v-if="col.slotName=='time'" #default="scope">
                    <span>{{ parseTime(scope.row[col.prop]) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="60" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" size="small" icon="View" @click="handelView(scope.row)">查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </div>
</template>

<script setup name="AlarmRecord">

import {appendDateRange} from "@/utils/hazard.js";
import {getHazardAlarmRecords} from "@/api/business/hazard.js";
import {parseTime} from "../../utils/ruoyi.js";
import {useRouter} from "vue-router";

const router = useRouter()
const {proxy} = getCurrentInstance()

const showSearch = ref(true)
const list = ref([])
const loading = ref(true)
const total = ref(0)
const dateRangeReceive = ref([])
const dateRangeHandle = ref([])
const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        hazardId: undefined,
        handled: undefined,
        type: undefined
    }
})

const handleOptions = ref([
    {label: '未读', value: false},
    {label: '已读', value: true}
])
const typeOptions = ref([
    {label: '逾期', value: false},
    {label: '即将到期', value: true}
])
// 列显隐信息
const columns = ref([
    {key: 0, label: `序号`, visible: true, prop: 'id', width: 80},
    {key: 1, label: `被通知人`, visible: false, prop: 'receiver', width: 100},
    {key: 2, label: `通知类型`, visible: true, prop: 'type', width: 100},
    {key: 3, label: `通知状态`, visible: true, prop: 'handled', width: 100, slotName: 'handle'},
    {key: 4, label: `隐患序号`, visible: true, prop: 'hazardIds', minWidth: 150},
    {key: 5, label: `通知时间`, visible: true, prop: 'receiveTime', width: 160, slotName: 'time'},
    {key: 6, label: `已读时间`, visible: true, prop: 'handleTime', width: 160, slotName: 'time'},
    {key: 7, label: `最后已读时间`, visible: false, prop: 'lastHandleTime', width: 160, slotName: 'time'},
])

const {
    queryParams
} = toRefs(data)

function mergeParams() {
    // merge into a new object.
    let query = {...queryParams.value} // make a copy
    query = appendDateRange(query, dateRangeReceive.value, 'receiveTime')
    query = appendDateRange(query, dateRangeHandle.value, 'handleTime')
    return query
}

/** 查询隐患列表 */
function getList() {
    loading.value = true
    return getHazardAlarmRecords(mergeParams()).then(res => {
        list.value = res.rows
        total.value = res.total
    }).finally(() => loading.value = false)
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    dateRangeReceive.value = []
    dateRangeHandle.value = []
    proxy.resetForm("queryRef")
    handleQuery()
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download("alarmRecord/export", mergeParams(), `隐患通知导出_${new Date().getTime()}.xlsx`)
}

function handelView(row) {
    const {id, type, hazardIds} = row
    const hazardCount = hazardIds ? hazardIds.split(',').length : 0
    if (!hazardIds) return proxy.$modal.msg('没有隐患可供查看')

    const payload = {id, tag: `${type}通知（${hazardCount}）`}
    const query = {alarm: encodeURIComponent(JSON.stringify(payload))}
    router.push({path: '/docs/hazard/list', query})
}

let isFirstMount = false
onMounted(async () => {
    isFirstMount = true
    await getList()
    isFirstMount = false
})
onActivated(() => {
    // 这里应该是若依的BUG，从菜单初次进入此页时，mount和activate会同时触发
    if (isFirstMount) return // 防止重复调用
    getList()
})
</script>

<style scoped>

</style>